import 'package:flutter/material.dart';
import 'package:flutter_widget_from_html_core/flutter_widget_from_html_core.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/exam/dto/assessment.response.dart';
import 'package:ichinesereader/exam/util/ExamLayoutUtil.dart';
import 'package:intl/intl.dart';

import 'BGAPExamController.dart';
import 'BGAPExamQuestionIndexPage.dart';
import 'BGAPExamSectionPage.dart';
import 'BGCountDown.dart';

class BGAPExamPage extends GetView<BGAPExamController> {
  BGAPExamPage({Key? key}) : super(key: key);
  final String? assessmentId = Get.arguments['id'];
  final String title = 'Assessment';

  @override
  Widget build(BuildContext context) {
    delayedLoadData();
    return Scaffold(
        appBar: AppBar(
          title: Text(title),
          centerTitle: true,
        ),
        body: WillPopScope(
            onWillPop: () async {
              controller.reportCurrentPageRecord();
              return true;
            },
            child: Obx(() => _buildExam())));
  }

  void delayedLoadData() {
    Future.delayed(const Duration(milliseconds: 10), () {
      controller.loadData(assessmentId!);
    });
  }

  Widget _buildExam() {
    return controller.isTestCompleted.value ? _buildTestCompletedPage() : _buildMainExam();
  }

  Widget _buildMainExam() {
    return Padding(
        padding: const EdgeInsets.all(20.0),
        child: Column(
          children: [_buildExamTop(), Expanded(child: _buildExamMain()), _buildExamBottom()],
        ));
  }

  Widget _buildExamTop() {
    return Obx(() {
      // ignore: unused_local_variable
      var currentQuestionStepIndex = controller.currentQuestionStepIndex.value; //起到订阅作用
      var questionIndexTitle = Row(children: []);

      if (controller.currentUiPartIndex != null) {
        // Part1 >
        if (controller.assessmentResult!.list!.length > 1) {
          questionIndexTitle.children.add(Text('${controller.currentUiPartIndex?.name} > ',
              style: TextStyle(fontWeight: FontWeight.normal, color: (Get.isDarkMode ? Color(0xFF757575) : Colors.black87), fontSize: 20)));
        }
      }
      if (controller.currentQuestionStep?.stepType == UiQuestionStep.STEPTYPE_QUESTION) {
        // Q1 >
        questionIndexTitle.children.add(
            Text('${controller.currentUiSectionIndex?.name} > ', style: TextStyle(fontWeight: FontWeight.normal, color: Colors.blue, fontSize: 18)));
        // Question 1 of 15  Step=1
        questionIndexTitle.children.add(Text(
            ' Question ${(controller.currentQuestionStep?.questionIndex ?? 0) + 1} of ${controller.currentUiSectionIndex?.questionIndexList?.length}'));
      }

      Widget rightWidget;
      if (controller.isTest.value) {
        QuestionPart? questionPart = controller.assessmentResult?.list![controller.currentQuestionStep?.partIndex ?? 0];
        UiQuestionStep? uiQuestionStep = controller.currentQuestionStep;
        rightWidget = Row(children: [
          OutlinedButton(
              onPressed: () {
                controller.isHideTimer.value = !controller.isHideTimer.value;
              },
              child: Text(controller.isHideTimer.value ? 'SHOW' : 'HIDE')),
          SizedBox(
              width: controller.isHideTimer.value ? 0 : 92,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  SizedBox(width: 5),
                  Icon(Icons.watch_later_outlined, color: Colors.red, size: 18),
                  SizedBox(width: 3),
                  BGCountdown(
                    controller: controller.timerVC,
                    seconds: controller.countSeconds.value,
                    build: (_, double time) {
                      int minutes = time ~/ 60;
                      int seconds = (time % 60).toInt();
                      String minute = minutes.toString();
                      if (minutes <= 9) {
                        minute = "0" + minute;
                      }
                      String second = seconds.toString();
                      if (seconds <= 9) {
                        second = "0" + second;
                      }
                      return Text(
                        '$minute: $second',
                        style: TextStyle(fontSize: 18, color: Colors.red),
                      );
                    },
                    onFinished: () {
                      if (uiQuestionStep?.stepType == UiQuestionStep.STEPTYPE_PARTPROMPT) {
                        controller.isNextPageEnable.value ? _onNextPage() : _onSubmitRecordAction();
                      }
                      if (uiQuestionStep?.stepType == UiQuestionStep.STEPTYPE_QUESTION) {
                        if (questionPart?.partType != null && questionPart?.partType == 'SPEAKING') {
                          if (controller.speakActionNum.value == 1) {
                            controller.speakActionNum.value = 2;
                          } else {
                            if (controller.currentQuestionStepBody.value.prepareTime != null) controller.dealPrepareTimeSpeakingAction();
                          }
                        } else {
                          controller.isNextPageEnable.value ? _onNextPage() : _onSubmitRecordAction();
                        }
                      }
                    },
                  ),
                  SizedBox(width: 5)
                ],
              ))
        ]);
      } else {
        rightWidget = OutlinedButton(
            onPressed: () async {
              showGeneralDialog(
                  context: Get.context!,
                  transitionDuration: const Duration(milliseconds: 400),
                  pageBuilder: (bc, ania, anis) {
                    // 索引页面
                    return BGAPExamQuestionIndexPage();
                  });
            },
            child: const Text('INDEX'));
      }

      return Row(
        children: [questionIndexTitle, const Expanded(child: SizedBox()), rightWidget],
      );
    });
  }

  Widget _buildExamMain() {
    return Container(
        decoration: ExamLayoutUtil.getBoxDecoration(),
        width: double.infinity,
        child: Padding(
            padding: const EdgeInsets.all(10),
            child: Obx(() {
              Widget? partContent;
              // ignore: unused_local_variable
              var currentQuestionStepIndex = controller.currentQuestionStepIndex.value;
              UiQuestionStep? uiQuestionStep = controller.currentQuestionStep;
              if (uiQuestionStep?.stepType == UiQuestionStep.STEPTYPE_PARTPROMPT) {
                partContent = _buildPartStartPromptPage();
              } else if (uiQuestionStep?.stepType == UiQuestionStep.STEPTYPE_QUESTION) {
                partContent = const BGAPExamSectionPage();
              } else {
                partContent = const Center(child: CircularProgressIndicator());
              }
              return partContent;
            })));
  }

  void _onNextPage() async {
    controller.nextPage();
  }

  void _onSubmitRecordAction() async {
    controller.submitAction();
  }

  void _alertTipsIsLastAction() {
    Get.snackbar('Message', 'This is the last question of reading!', snackPosition: SnackPosition.TOP);
  }

  Widget _buildExamBottom() {
    void _onPrevPage() async {
      controller.prevPage();
    }

    void _onSubmitAction() async {
      List numList = controller.verifyCompleteAllQuestion();
      if (numList.isEmpty) {
        controller.submitAction();
      } else {
        showQuestionDialog(Get.context!, numList);
      }
    }

    return Obx(() {
      QuestionPart? questionPart = controller.assessmentResult?.list![controller.currentQuestionStep?.partIndex ?? 0];
      if (controller.isTest.value) {
        UiQuestionStep? uiQuestionStep = controller.currentQuestionStep;
        if (questionPart?.partType != null && questionPart?.partType == 'READING' && uiQuestionStep?.stepType == UiQuestionStep.STEPTYPE_QUESTION) {
          var currentQuestionStepIndex = controller.currentQuestionStepIndex.value;
          UiQuestionStep? preStep = uiQuestionStep;
          if (currentQuestionStepIndex > 0) {
            preStep = controller.questionStepList[currentQuestionStepIndex - 1];
          }
          UiQuestionStep? nextStep = uiQuestionStep;
          if (currentQuestionStepIndex < controller.questionStepList.length - 2) {
            nextStep = controller.questionStepList[currentQuestionStepIndex + 1];
          }
          return Row(
            children: [
              const Expanded(child: SizedBox()),
              Row(
                children: [
                  OutlinedButton(
                      onPressed: (controller.isPrevPageEnable.value && preStep?.stepType != UiQuestionStep.STEPTYPE_PARTPROMPT) ? _onPrevPage : null,
                      child: const Text('PREV')),
                  const SizedBox(width: 10),
                  OutlinedButton(
                      onPressed: () {
                        if (nextStep?.stepType == UiQuestionStep.STEPTYPE_PARTPROMPT &&
                            (controller.currentQuestionStepBody.value.answer == null ||
                                controller.currentQuestionStepBody.value.answer!.length < 1)) {
                          _alertTipsIsLastAction();
                        } else {
                          controller.isNextPageEnable.value ? _onNextPage() : _onSubmitAction();
                        }
                      },
                      style: ButtonStyle(
                          backgroundColor: MaterialStateProperty.all(
                              (nextStep?.stepType == UiQuestionStep.STEPTYPE_PARTPROMPT) ? Colors.blueGrey : Colors.transparent)),
                      child: controller.isNextPageEnable.value ? const Text('NEXT') : const Text('SUBMIT'))
                ],
              ),
            ],
          );
        } else {
          return SizedBox();
        }
      }
      return Row(
        children: [
          const Expanded(child: SizedBox()),
          Row(
            children: [
              OutlinedButton(onPressed: controller.isPrevPageEnable.value ? _onPrevPage : null, child: const Text('PREV')),
              const SizedBox(width: 10),
              OutlinedButton(
                  onPressed: controller.isNextPageEnable.value ? _onNextPage : _onSubmitAction,
                  child: controller.isNextPageEnable.value ? const Text('NEXT') : const Text('SUBMIT'))
            ],
          ),
        ],
      );
    });
  }

  Widget _buildPartStartPromptPage() {
    UiQuestionStep? uiQuestionStep = controller.currentQuestionStep;
    int partIndex = uiQuestionStep?.partIndex ?? 0;
    QuestionPart? questionPart = controller.assessmentResult?.list![partIndex];
    String introduction = questionPart?.introduction ?? '';
    String questionTitle = '';
    if (Get.arguments != null) questionTitle = Get.arguments['questionTitle'];
    if (introduction.isEmpty) {
      introduction = questionTitle;
    }
    return Container(
        width: double.infinity,
        child: Padding(
          padding: EdgeInsets.all(20),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              HtmlWidget(introduction,
                  textStyle: TextStyle(fontSize: 18, color: (Get.isDarkMode ? Color(0xFF757575) : Colors.black87), height: 1.8, wordSpacing: 1.5)),
              HtmlWidget('© iChineseReader ${DateFormat('yyyy').format(DateTime.now()).toString()}',
                  textStyle: TextStyle(fontSize: 18, color: (Get.isDarkMode ? Color(0xFF757575) : Colors.black87), height: 1.8, wordSpacing: 1.5)),
            ],
          ),
        ));
  }

  Widget _buildTestCompletedPage() {
    List<Widget> options = [];
    String titleStr = '';
    String content = '';
    titleStr = 'Congratulations! You finished the test!';
    content = 'Thank you for your time!';

    options.add(Text(titleStr,
        textAlign: TextAlign.center,
        style: TextStyle(fontSize: 30, color: Get.isDarkMode ? Colors.white70 : Colors.black87, fontWeight: FontWeight.w600)));
    options.add(SizedBox(height: 20));

    options.add(Icon(Icons.check_circle, size: 100, color: Colors.green));
    options.add(SizedBox(height: 10));

    options.add(Text(content,
        textAlign: TextAlign.center,
        style: TextStyle(fontSize: 20, height: 1.8, wordSpacing: 1.5, color: Get.isDarkMode ? Colors.white70 : Colors.black87)));
    options.add(SizedBox(height: 30));
    options.add(MaterialButton(
        minWidth: 140,
        height: 45,
        color: Colors.green,
        textColor: Colors.white,
        child: Text('Test Finished', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(6.0),
            side: BorderSide(
              color: Color(0xff8AAAA4),
            )),
        onPressed: () {
          Future.delayed(Duration(milliseconds: 500), () {
            Get.back();
          });
        }));
    return Padding(
        padding: const EdgeInsets.all(20.0),
        child: Container(
            decoration: ExamLayoutUtil.getBoxDecoration(),
            width: double.infinity,
            child: Padding(padding: const EdgeInsets.all(50), child: Column(children: options))));
  }

  void showQuestionDialog(BuildContext context, List list) async {
    await showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
            title: Text('Are you sure you want to submit?',
                textAlign: TextAlign.center, style: TextStyle(color: Color(0xff3d6f8c), fontSize: 22, fontWeight: FontWeight.w500)),
            content: SizedBox(
                width: 350,
                height: list.isEmpty ? 10 : 200,
                child: list.isEmpty
                    ? SizedBox()
                    : Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                        Text('Undone Index:', style: TextStyle(color: Get.isDarkMode ? Colors.white : Colors.red, fontSize: 18)),
                        SizedBox(height: 10),
                        Expanded(
                            child: Scrollbar(
                                thumbVisibility: true,
                                child: SingleChildScrollView(
                                    primary: true,
                                    child: Text(list.toString(),
                                        style: TextStyle(color: Get.isDarkMode ? Colors.white60 : Color(0xFF212529), fontSize: 16, height: 1.5)))))
                      ])),
            shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(10.0))),
            contentPadding: const EdgeInsets.fromLTRB(24, 15, 24, 30),
            actions: <Widget>[
              TextButton(
                  child: Text('Cancel', style: TextStyle(color: Colors.grey, fontSize: 16)),
                  onPressed: () {
                    Get.back();
                  }),
              TextButton(
                  child: Text('Submit', style: TextStyle(fontSize: 16)),
                  onPressed: () {
                    Get.back();
                    controller.submitAction();
                  })
            ]);
      },
    );
  }
}
